#include <iostream>
#include "Common.hpp"
#include "InetAddr.hpp"

void Usage(std::string proc)
{
    std::cerr << "Usage: " << proc << "server_ip server_port" << std::endl;
}
int main(int argc, char* argv[])
{
    if(argc != 3)
    {
        Usage(argv[0]);
        exit(USAGE_ERR);
    }

    //通过参数拿出服务器的ip和端口号
    std::string ip = argv[1];
    uint16_t port = std::stoi(argv[2]);
    int sockfd = socket(AF_INET, SOCK_STREAM, 0);//前两个参数确定是IPV4的TCP协议
    if(sockfd < 0)
    {
        std::cerr << "socket error" << std::endl;
        exit(SOCKET_ERR);
    }

    //发起建立连接请求
    Inet_Addr addr(ip, port);
    int n = connect(sockfd, addr.INetAddr(), addr.NetAddrLen());
    if(n < 0)
    {
        std::cerr << "connect error" << std::endl;
        exit(CONNECT_ERR);
    }

    while(true)
    {
        std::string line;
        std::cout << "Please Enter@ ";
        std::getline(std::cin, line);

        //将信息发送给服务器
        write(sockfd, line.c_str(), line.size());

        //读取服务器的信息
        char buffer[1024];
        ssize_t size = read(sockfd, buffer, sizeof buffer);
        if(size > 0)
        {
            buffer[size] = 0;
            std::cout << "server echo# " << buffer << std::endl;
        }
    }
    close(sockfd);
    return 0;
}
